<?php


namespace App\Http\Controllers;

use App\Models\Token;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseController
{
    public function setPwd($pwd){
        return md5(md5($pwd));
    }

    public function setToken($user_id, $role = 0){
        $token = md5(time() . $user_id);

        Token::insert([
            'user_id' => $user_id,
            'token' => $token,
            'is_admin' => $role,
            'created_at' => time()
        ]);

        return $token;
    }

    public function userSignup(Request $request){
        $only = $request->only(['username', 'password']);

        $validator = Validator::make($only, [
            'username' => 'required|min:4|max:60',
            'password' => 'required|min:8|max:60'
        ], []);

        if ($validator->fails()){
            return $this->returnInvalid($validator->errors()->getMessages());
        }

        if (User::where('username', $only['username'])->value('username') != null){
            return $this->returnInvalid([
                'username' => [
                    'message' => 'unique'
                ]
            ]);
        }

        $user_id = User::insertGetId([
            'username' => $only['username'],
            'password' => $this->setPwd($only['password']),
            'last_login_timestamp' => time(),
            'created_at' => time(),
        ]);

        return $this->returnJson(['token' => $this->setToken($user_id)],self::NEW_RESOURCES);
    }

    public function userSignin(Request $request){
        $only = $request->only(['username', 'password']);

        $validator = Validator::make($only, [
            'username' => 'required|min:4|max:60',
            'password' => 'required|min:8|max:60'
        ], []);

        if ($validator->fails()){
            return $this->returnInvalid($validator->errors()->getMessages());
        }

        $user = User::where([
            'username' => $only['username'],
            'password' => $this->setPwd($only['password']),
        ]);


        if ($user->first() == null){
            return $this->returnJson([],self::WRONG,"invalid", "Wrong username or password");
        }

        $user->update(['last_login_timestamp' => time()]);

        return $this->returnJson(['token' => $this->setToken($user->value('id'))]);
    }

    public function userSignout(Request $request){
        $token = $request->user->token;

        Token::where('token', $token)->delete();

        return $this->returnJson();
    }
}
